package com.yylending.las.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.PermissionChecker;
import com.yyfax.common.CLog;

/**
 * Created by laixj on 2016/11/30.
 */
public class PermissionUtil {

	public final static String TAG = "PermissionUtil";

	public static void requestPermission(Activity context, String[] permission, int requestCode) {
		ActivityCompat.requestPermissions(context, permission, requestCode);
	}

	public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
		fragment.requestPermissions(permission, requestCode);
	}

	public static boolean checkAppPermissionWithVersion(Context context, String permission) {
		return isSdkUnderM() || checkAppPermission(context, permission);
	}

	public static boolean isSdkUnderM() {
		return Build.VERSION.SDK_INT < Build.VERSION_CODES.M;
	}

	public static boolean checkAppPermission(Context context, String permission) {
		boolean result = (PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED);//ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
		if (result) {
			CLog.i(TAG, "有" + permission + "这个权限");
		} else {
			CLog.i(TAG, "木有" + permission + "这个权限");
		}
		return result;
	}

	public static boolean isAlwaysDenied(Activity activity, String permission) {
		return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
	}

	public static boolean checkCameraPermission() {
		boolean result = true;
		Camera mCamera = null;
		try {
			mCamera = Camera.open();
			// setParameters 是针对魅族做的。MX5 通过Camera.open() 拿到的Camera
			// 对象不为null
			Camera.Parameters mParameters = mCamera.getParameters();
			mCamera.setParameters(mParameters);
		} catch (Exception e) {
			result = false;
			CLog.i(TAG, "判断相机权限" + e.toString());
		} finally {
			if (mCamera != null) {
				mCamera.release();
				mCamera = null;
			}
		}
		return result;
	}

	public static boolean isGranted(int code) {
		return PackageManager.PERMISSION_GRANTED == code;
	}

	/**
	 * 判断GPS是否开启
	 *
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean isGpsOPen(Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		return gps;
	}
}
